package com.scalar.chiptrack.finance.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.finance.forms.CostReportsForm;
import com.scalar.chiptrack.finance.dao.UpdateViewCostDAO;
import com.scalar.chiptrack.finance.dao.FinanceDataDumpReportDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
import org.apache.poi.ss.usermodel.Workbook;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: sujankumar.suppala
 * Date: Mar 28, 2006
 * Time: 6:01:32 PM
 */
public class CostReportAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/costReportAction.do";
    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        CostReportsForm costReportsForm = (CostReportsForm)form;
        String action = request.getParameter( "action" );

        HashMap<String, String> info    = new HashMap<String, String>();
        HashMap<String, String> errors  = new HashMap<String, String>();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        HttpSession session = request.getSession ();
        Workbook workbook = null;
        String fileName = "";
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        if ( "standardCostReport".equalsIgnoreCase( action ) || Constants.ACTION_CALCULATE_COST.equalsIgnoreCase( action ) )
        {
            String processTypeName          = request.getParameter( "processTypeName" );

            /*if ( processTypeName != null && "Mark and Pack".equalsIgnoreCase(processTypeName) )
            {
                processTypeName = "Mark & Pack";
            }*/

            ArrayList<LabelValueBean> partNumberList    = new ArrayList<LabelValueBean>();
            ArrayList<LabelValueBean> vendorList        = new ArrayList<LabelValueBean>();
            try
            {
                if( processTypeName == null || "0".equalsIgnoreCase ( processTypeName ) )
                {
                   partNumberList = NewProductDAO.loadAllBaseProducts( null, true, true );

                    ArrayList vendorTempList = VendorDAO.getAllVendors();
                    vendorList.add(new org.apache.struts.util.LabelValueBean("All Vendors","0"));
                    for(int i=0; i <  vendorTempList.size() ; i++ )
                    {
                       Vendor vendor =  ( Vendor ) vendorTempList.get ( i );
                       vendorList.add( new org.apache.struts.util.LabelValueBean ( vendor.getVendorName() , Integer.toString(vendor.getVendorId()) ) );
                    }
                }
                else
                {
                   partNumberList = NewProductDAO.loadPartNumbers( null, 0, processTypeName, true, true, true, 0 );
                   vendorList = VendorDAO.getVendorNamesByProcessByUserType( null, processTypeName, user );
                }

            }
            catch ( ScalarException e )
            {
                e.printStackTrace();
                errors.put ( "Could not load search field values", null );
            }

            if ( Constants.ACTION_CALCULATE_COST.equalsIgnoreCase( action ) )
            {
                boolean success = false;
                try
                {
                    UpdateViewCostDAO.calculateCost( null );
                    success = true;
                }
                catch ( ScalarException se )
                {
                    se.printStackTrace();
                    errors.put ("Could not Calculate Cost", null);
                    success = false;
                }
                if( success )
                {
                    info.put ( "Cost calculations successfully done", null );
                }
            }

            request.setAttribute ( "processTypeNameList", NewProductDAO.loadAllProcessesFromDB(null, true ) );
            request.setAttribute ( "partNumberList", partNumberList );
            request.setAttribute ( "vendorList", vendorList );

            return mapping.findForward( "standardCostReport" );
        }
        else if ( "yieldedCostReport".equalsIgnoreCase( action ) )
        {
            ArrayList baseProductList = new ArrayList();
            try
            {
                baseProductList = ProductDao.loadAllBaseProducts( null );
            }
            catch ( ScalarException e )
            {
                errors.put ( "Could not load base products", null );
            }
            request.setAttribute ( "baseProductList", baseProductList );
            return mapping.findForward( "yieldedCostReport" );
        }
        else if ( "performanceCostReport".equalsIgnoreCase( action ) )
        {
            ArrayList baseProductList = new ArrayList();
            try
            {
                baseProductList = ProductDao.loadAllBaseProducts( null );
            }
            catch ( ScalarException e )
            {
                errors.put ( "Could not load base products", null );
            }
            request.setAttribute ( "baseProductList", baseProductList );
            return mapping.findForward( "performanceCostReport" );
        }
        else if ("xlsdetailCostReport".equalsIgnoreCase( action ) )
        {
            costReportsForm.setFromDate(request.getParameter("prompt4") );
            String reportName = "Standrad Cost Report";
            if ("prjcostdetail".equalsIgnoreCase(costReportsForm.getReportType()) )
            {
                 reportName = "Standrad Vs Projected Cost Report";
            }
            ArrayList stdCostLotsList = FinanceDataDumpReportDAO.getStdCostReport ( null, costReportsForm );

            workbook =  DataDumpReportsHelper.getWorkbook( stdCostLotsList, reportName, null, null, null ) ;

            fileName = reportName + "_"+ DateUtil.getTimeStamp() ;

            ExcelUtils.generateExcelReport( workbook, fileName, response );
        }
        return null;
    }
}
